package com.sunnay.controller;

import com.sunnay.annotation.Login;
import com.sunnay.constant.GbRedisKey;
import com.sunnay.service.AppUserInfoService;
import com.sunnay.util.R;
import com.sunnay.util.RedisUtil;
import com.sunnay.vo.auth.LoginAuthVo;
import com.sunnay.vo.auth.LoginVo;
import com.sunnay.vo.auth.SystemUser;
import com.sunnay.vo.user.UserInfoVo;
import com.sunnay.web.ContextHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/auth")
public class LoginController {

    @Resource
    private AppUserInfoService appUserInfoService;

    @Resource
    private RedisUtil redisUtil;

    @Login(require = false)
    @PostMapping("/user-login")
    public R<LoginAuthVo> login(@RequestBody LoginVo loginVo){
        LoginAuthVo authVo = appUserInfoService.login(loginVo);
        setLoginUser(authVo);
        return R.ok(authVo);
    }

    /**
     * 用户基本信息
     */
    @GetMapping("/info")
    public R<UserInfoVo> userInfo(){
        return R.ok(appUserInfoService.userInfo(ContextHelper.getSystemUser()));
    }

    @PostMapping("logout")
    public R<Boolean> logout() {
        SystemUser systemUser = ContextHelper.getSystemUser();
        if (systemUser.getId() != null) {
            if (StringUtils.isNotBlank(systemUser.getOnlineKey())) {
                HttpSession session = ContextHelper.getSession(false);
                if (session != null) {
                    Object hashObject = redisUtil.getHashObject(String.format(GbRedisKey.GB_ONLINE_KEY,session.getId()), systemUser.getOnlineKey());
                    if (session.getId().equals(hashObject)) {
                        //删除redisKey
                        redisUtil.delHashObject(String.format(GbRedisKey.GB_ONLINE_KEY,session.getId()),systemUser.getOnlineKey());
                    }
                }
            }
        }
        ContextHelper.clearSystemUser();
        return R.ok();
    }


    private void setLoginUser(LoginAuthVo loginAuthVo) {
        // 获取当前session信息
        HttpSession session = ContextHelper.getSession(false);
        if (session != null) {
            ContextHelper.clearSystemUser(session);
        }
        session = ContextHelper.getSession(true);
        session.setMaxInactiveInterval(ContextHelper.SESSION_MAX_INACTIVE_INTERVAL_DEFAULT);

        // 存入sessionId
        String oldSessionId = (String) redisUtil.setHashObject(String.format(GbRedisKey.GB_ONLINE_KEY,session.getId()), loginAuthVo.getSystemUser().getOnlineKey(), session.getId());

        if (StringUtils.isNotBlank(oldSessionId) && !oldSessionId.equals(session.getId())) {
            //踢人名单
            redisUtil.setHashObject(GbRedisKey.GB_ONLINE_KICK_KEY, oldSessionId, StringUtils.EMPTY);
        }
        // 设置session
        session.setAttribute(ContextHelper.USER_INFO,loginAuthVo.getSystemUser());
    }
}
